package com.leven.weatherdemo.model.impl;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.leven.weatherdemo.model.WeatherModel;
import com.leven.weatherdemo.model.entity.Weather;
import com.leven.weatherdemo.presenter.OnWeatherLitener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WeathreModel
 * Created by Administrator on 2016/8/16.
 */
public class WeatherModelImpl implements WeatherModel {
    //根据城市名称查询的API地址
    private static final String URL = "http://service.envicloud.cn:8082/api/getWeatherForecast";
    //环境云分配的请求ID
    private static final String ACCESSID = "ZGVTBZE0NDI5MDM0MJAZNDC=";

    private RequestQueue requestQueue;
    private Gson gson = new Gson();


    public WeatherModelImpl(Context context) {

        requestQueue = Volley.newRequestQueue(context);
    }

    @Override
    public void loadWeather(String cityName, OnWeatherLitener litener) {

        doGet(cityName, litener);
    }

    private void doGet(String cityName, final OnWeatherLitener litener) {
        String url = URL + "?cityname=" + cityName + "&ak=" + ACCESSID;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                System.out.println(s);
                //将json字符串转换为weather对象
                Weather weather = gson.fromJson(s, Weather.class);
                //如果weather的resultCode==0证明查询数据成功
                if ("0".equals(weather.getResultCode())) {
                    //调用listener的onSuccess（）方法，通知数据查询成功，更新数据。
                    litener.onSuccess(weather);
                } else {
                    //数据查询失败
                    litener.onFiled();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //数据查询失败
                System.out.println("ERROR" + volleyError.getMessage());
                litener.onFiled();
            }
        });

        //执行post请求
        requestQueue.add(stringRequest);
    }

}
